package com.nit.lab.controller.basic;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nit.lab.dto.basic.UserDTO;
import com.nit.lab.dto.system.TokenDTO;
import com.nit.lab.dto.utils.OpResultDTO;
import com.nit.lab.dto.utils.TableReqDTO;
import com.nit.lab.dto.utils.TableRspDTO;
import com.nit.lab.entity.basic.UserEntity;
import com.nit.lab.service.basic.UserService;
import com.nit.lab.utils.HttpRequestReader;
import com.nit.lab.utils.JWTUtil;

import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/api/user")
public class UserController {

    @Resource
    private UserService userService;
    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value(value="${application.jwt.expire}")
    private Integer expire;
    /**
     * @Description: 获取数据列表
     * @Author: SN
     * @Date: 2018/10/30 18:15
     */
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public TableRspDTO list4Table(@RequestHeader(name = "Access-Token") String token, @RequestBody TableReqDTO tableReqDTO) {
        TableRspDTO tableRspDTO = new TableRspDTO();
        try {
            TokenDTO tokenDTO = JWTUtil.verifyToken(token);
            tableRspDTO = userService.list4Table(tableReqDTO);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return tableRspDTO;
    }

    /**
     * @Description: 新增记录
     * @Author: SN
     * @Date: 2019/01/31 11:02
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public OpResultDTO add(@RequestHeader(name = "Access-Token") String token, @RequestBody UserDTO userDTO) {
        OpResultDTO opResult = new OpResultDTO();
        try {
            TokenDTO tokenDTO = JWTUtil.verifyToken(token);
            opResult.setMessage(userService.add(userDTO).toString());
        } catch (Exception e) {
            logger.error(e.toString());
            opResult.setMessage("error");
        }
        return opResult;
    }

    /**
     * @Description: 更新记录
     * @Author: SN
     * @Date: 2019/01/31 11:02
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public OpResultDTO update(@RequestBody UserDTO userDTO) {
        OpResultDTO opResult = new OpResultDTO();
        try {
            opResult.setMessage(userService.update(userDTO).toString());
        } catch (Exception e) {
            logger.error(e.toString());
            opResult.setMessage("error");
        }
        return opResult;
    }

    /**
     * @Description: 删除记录
     * @Author: SN
     * @Date: 2019/01/31 11:02
     */
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    public OpResultDTO remove(HttpServletRequest request) {
        OpResultDTO opResult = new OpResultDTO();
        try {
            JSONObject jsonRequest = HttpRequestReader.getJsonObject(request);
            String userIds = jsonRequest.getString("userIds");
            opResult.setMessage(userService.remove(userIds).toString());
        } catch (Exception e) {
            logger.error(e.toString());
            opResult.setMessage("error");
        }
        return opResult;
    }

    /**
     * @Description: 重置密码
     * @Author: SN
     * @Date: 2019/01/31 11:02
     */
    @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
    public OpResultDTO resetPwd(@RequestBody UserDTO userDTO) {
        OpResultDTO opResult = new OpResultDTO();
        try {
            opResult.setMessage(userService.resetPwd(userDTO.getUserId(), userDTO.getLoginPwd()).toString());
        } catch (Exception e) {
            logger.error(e.toString());
            opResult.setMessage("error");
        }
        return opResult;
    }

    /**
     * @Description: 登录账号重名验证
     * @Author: SN
     * @Date: 2020/02/31 11:02
     */
    @RequestMapping(value = "/validateLoginName", method = RequestMethod.POST)
    public OpResultDTO validateLoginName(HttpServletRequest request) {
        OpResultDTO opResult = new OpResultDTO();
        try {
            JSONObject jsonRequest = HttpRequestReader.getJsonObject(request);
            String loginName = jsonRequest.getString("loginName");
            if (userService.loginCheck(loginName) == null) {
                opResult.setMessage("success");
            } else {
                opResult.setMessage("error");
            }
        } catch (Exception e) {
            logger.error(e.toString());
            opResult.setMessage("error");
        }
        return opResult;
    }
    /**
     * @Description: 根据Id获取信息
     * @Author: lxr
     * @Date: 2020/03/25
     */
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    public OpResultDTO getInfo(@RequestHeader(name = "Access-Token") String token) {
        OpResultDTO opResult = new OpResultDTO();
        try {
            TokenDTO tokenDTO = JWTUtil.verifyToken(token);
            opResult.setMessage("success");
            opResult.setResult(userService.getByUserId(tokenDTO.getAccountId()));
        } catch (Exception e) {
            logger.error(e.toString());
            opResult.setMessage("error");
        }
        return opResult;
    }

    /**
     * @Description: 更新用户状态
     * @Author: SN
     * @Date: 2019/01/31 11:02
     */
    @RequestMapping(value = "/updateUserType", method = RequestMethod.POST)
    public OpResultDTO updateUserType(HttpServletRequest request) {
        OpResultDTO opResult = new OpResultDTO();
        try {
            JSONObject jsonRequest = HttpRequestReader.getJsonObject(request);
            Long userId = jsonRequest.getLong("userId");
            opResult.setResult(userService.updateUserType(userId));
        } catch (Exception e) {
            logger.error(e.toString());
            opResult.setMessage("error");
        }
        return opResult;
    }

    /**
     * @description: 获取用户信息
     * @Author: WJM
     * @Date: 2022/6/30 20:14
     **/
    @RequestMapping(value = "/listAll", method = RequestMethod.POST)
    public OpResultDTO listAll() {
        OpResultDTO opResult = new OpResultDTO();
        try {
            opResult.setResult(userService.getUserListAll());
            opResult.setMessage("success");
        } catch (Exception e) {
            logger.error(e.toString());
            opResult.setMessage("error");
        }
        return opResult;
    }

    /**
     * @description: 获取openid或是用户信息
     * @Author: LYN
     * @Date: 2022/6/30 20:14
     **/
    @RequestMapping(value = "/getOpenId",method = RequestMethod.POST)
    public JSONObject getOpenId(@RequestBody String code) throws Exception {
        JSONObject jsonObject = JSON.parseObject(code);
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1 = userService.getOpenId((String) jsonObject.get("code"));
            if((Integer) jsonObject1.get("ans")==0){
                jsonObject1.put("message","success");
            }
            else{
                UserDTO userDto = (UserDTO)jsonObject1.get("user");
                TokenDTO tokenDTO = new TokenDTO();
                tokenDTO.setAccountId(userDto.getUserId());
                tokenDTO.setUnitId(userDto.getUnitId());
                tokenDTO.setUnitFather(userDto.getUnitFather());
                tokenDTO.setUnitType(userDto.getUnitType());
                jsonObject1.put("token",JWTUtil.createSign(tokenDTO.toString(),expire));
                jsonObject1.put("message","success");
            }
        }catch (Exception e){
            logger.error(e.toString());
            jsonObject1.put("message","error");
        }

        return jsonObject1;
    }

    /**
     * @description: 获取phone
     * @Author: LYN
     * @Date: 2022/6/30 20:14
     **/
    @RequestMapping(value = "/getPhone",method = RequestMethod.POST)
    public String getPhone(@RequestBody String code) throws Exception {
        JSONObject jsonObject = JSON.parseObject(code);
        String code2 = (String)jsonObject.get("code");
        String res = null ;
        try {
            res = userService.getPhone(code2);
        }
        catch (Exception e){
            logger.error(e.toString());
            res = "error";
        }
        return res;
    }

    @RequestMapping(value = "/weiadd", method = RequestMethod.POST)
    public JSONObject weiadd(@RequestBody JSONObject jsonObject) {
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1 = userService.weiAdd(jsonObject);
            UserEntity userEntity = (UserEntity) jsonObject1.get("user");
            TokenDTO tokenDTO = new TokenDTO();
            tokenDTO.setAccountId(userEntity.getUserId());
            tokenDTO.setUnitId(userEntity.getUnitId());
            tokenDTO.setUnitFather(userEntity.getUnitFather());
            tokenDTO.setUnitType(userEntity.getUnitType());
            jsonObject1.put("token",JWTUtil.createSign(tokenDTO.toString(),expire));
            jsonObject1.put("result","success");
        } catch (Exception e) {
            logger.error(e.toString());
            jsonObject1.put("result","error");
        }
        return jsonObject1;
    }

    /**
     * @Description: 判断是否有准考证号
     * @Author: LYN
     * @Date: 2022/07/12
     */
    @RequestMapping(value = "/checkUser",method = RequestMethod.POST)
    public JSONObject checkUser(@RequestBody JSONObject jsonObject) throws Exception {
        JSONObject jsonObject1 = new JSONObject();
        String checkAdmiss = jsonObject.getString("admiss");
        String checkName = jsonObject.getString("name");
        System.out.println(checkAdmiss);
        System.out.println(checkName);
        try {
            if(userService.checkAdmiss(checkAdmiss)!=null){
                String name = userService.getCheckName(checkAdmiss);
                if(name.equals(checkName)){
                    jsonObject1.put("result","success");
                    jsonObject1.put("unit",userService.getCheckUnit(checkAdmiss));
                }
                else {
                    jsonObject1.put("checkName",name);
                    jsonObject1.put("result","error");
                }

            }
            else {
                jsonObject1.put("result","null");
            }
        }
        catch (Exception e){
            logger.error(e.toString());
            jsonObject1.put("result","wrong");

        }
        return jsonObject1;
    }

//  给小程序的
    /**
     * @Description: 根据用户的区块链号返回
     * @Author: LYN
     * @Date: 2022/07/17
     */
    @RequestMapping(value = "/checkAddress",method = RequestMethod.POST)
    public JSONObject checkAddress(@RequestBody JSONObject jsonObject1 ) throws Exception{
        JSONObject jsonObject = new JSONObject();
        String address = jsonObject1.getString("address");
        try {
            if(userService.getCheckAddress(address)!=null){
                jsonObject.put("result","successs");
                jsonObject.put("user",userService.getCheckAddress(address));
            }
            else {
                jsonObject.put("result","null");
            }

        }catch (Exception e){
            logger.error(e.toString());
            jsonObject.put("result","wrong");
        }
        return jsonObject;
    }
}
